//
//  CustomerInfoEditVc.m
//  WGFGlobalHouses
//
//  Created by waiguofang on 15/5/19.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//

#import "CustomerInfoEditVc.h"
#import "LocPickView.h"
#import "CompanyInfoEditView.h"
#import "config.h"

#import "StringTool.h"
#import "DatePickView.h"
#import "CustomerDataManage.h"
#import "MBProgressHUD+MJ.h"
#import "UserModal.h"
#import "SexView.h"
#import "ClearView.h"
#import "NSString+category.h"
#import "MessBtn.h"
#import "VPImageCropperViewController.h"
#import "PhootSelecteView.h"
#import "DealerDataManage.h"
#import "Tools.h"
#import "UIButton+WebCache.h"

@interface CustomerInfoEditVc ()<UITextFieldDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,VPImageCropperDelegate>
@property (weak, nonatomic) IBOutlet UIView *backView;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollview;

//真实姓名
@property (weak, nonatomic) IBOutlet UITextField *trueNameEt;

//身份认证
@property (weak, nonatomic) IBOutlet UITextField *rzEt;
@property (weak, nonatomic) IBOutlet UITextField *mobileEt;
@property (weak, nonatomic) IBOutlet UITextField *emailEt;
@property (weak, nonatomic) IBOutlet UITextField *phoneEt;
//性别
@property (weak, nonatomic) IBOutlet UITextField *sexEt;
@property (weak, nonatomic) IBOutlet UITextField *addressEt;
@property (weak, nonatomic) IBOutlet UITextField *birthEt;


@property (nonatomic,strong) LocPickView *locateView;
@property (nonatomic,strong) CompanyInfoEditView *editView;
@property (strong, nonatomic) DatePickView *dateView;
@property (nonatomic,strong)SexView *sexView;

@property (strong, nonatomic) CustomerDataManage *dataMange;

@property (nonatomic,copy)NSString *cityCode;
@property (nonatomic,copy)NSString *cityName;
@property (nonatomic,copy)NSString *stateCode;
@property (nonatomic,copy)NSString *stateName;

@property (nonatomic,strong)MessBtn *messBtn;
@property (nonatomic,strong)PhootSelecteView *menuView;
@property DealerDataManage *dm;

@property (weak, nonatomic) IBOutlet UIButton *headBtn;

@end

@implementation CustomerInfoEditVc
@synthesize locateView,editView,dateView,sexView,menuView,dm;

- (void)viewDidLoad {
    [super viewDidLoad];
    [self refreshData];
    [self initView];
   
}

-(CustomerDataManage *)dataMange
{
    if (!_dataMange) {
        _dataMange = [[CustomerDataManage alloc]init];
    }
    return _dataMange;
}

#pragma mark 初始化界面
-(void)initView
{
    
    dm = [[DealerDataManage alloc]init];
    //监听键盘
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBoardWillShow) name:UIKeyboardWillShowNotification object:nil];

    
    sexView = [SexView createView];
    [sexView.sureBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.titleView setMianTitle:@"信息管理"];


    [[self.titleView doneBtn] setImage:nil forState:UIControlStateNormal];
    
    [self.titleView.doneBtn setAttributedTitle:[NSString makeLineStyle:@"保存" color:[UIColor whiteColor] fontSize:14] forState:UIControlStateNormal];
    [[self.titleView doneBtn]setTag:100];
    [[self.titleView doneBtn]addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.rzEt setTintColor:[UIColor redColor]];
    [self.mobileEt setTintColor:[UIColor redColor]];
    [self.emailEt setTintColor:[UIColor redColor]];
    [self.phoneEt setTintColor:[UIColor redColor]];
    [self.trueNameEt setTintColor:[UIColor redColor]];
    [self.sexEt setTintColor:[UIColor redColor]];
    
    
    
}

-(void)upIU
{
    
    [self.headBtn setBackgroundColor:NoImgColor];
    
    [self.headBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:self.model.avatar] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"headtop_pic"]];

    if (![StringTool isBlankString:self.model.realname]) {
        self.trueNameEt.text = self.model.realname;
    }
    else
    {
        self.model.realname = @"";
    }
    
    if (![StringTool isBlankString:self.model.validateName]) {
        self.rzEt.text = self.model.validateName;
    }else
    {
        self.model.validate = @"";
    }
    
    if (![StringTool isBlankString:self.model.mobile]) {
        self.phoneEt.text = self.model.mobile;
    }else
    {
        self.model.mobile = @"";
    }
    
    self.sexEt.text = [self.model.sex isEqualToString:@"0"]?@"女":@"男";
    [sexView showhighlighted:self.sexEt.text];
    
    if (![StringTool isBlankString:self.model.birthday]){
        
        self.birthEt.text = self.model.birthday;
    }else
    {
        self.model.birthday = @"";
    }
    
    if (![StringTool isBlankString:self.model.mail]) {
        self.emailEt.text = self.model.mail;
    }else
    {
        self.model.mail = @"";
    }
    
    if (![StringTool isBlankString:self.model.tel]) {
        self.mobileEt.text = self.model.tel;
    }else
    {
        self.model.tel = @"";
    }
    
    if (![StringTool isBlankString:self.model.cityName]) {
        self.addressEt.text = self.model.cityName;
    }else
    {
        self.model.city = @"";
        self.model.cityName = @"";
        self.model.area = @"";
        self.model.areaName = @"";
    }
    
    if (![StringTool isBlankString:self.model.address]) {
        self.addressEt.text = self.model.address;
    }
    //    if (![StringTool isBlankString:self.model.areaName]) {
    //
    //        self.addressEt.text = [NSString stringWithFormat:@"%@-%@",self.model.cityName,self.model.areaName];
    //    }else
    //    {
    //        self.model.city = @"";
    //    }
    
    
    if ([StringTool isBlankString:self.model.account]) {
        self.model.account = @"";
    }
    if ([StringTool isBlankString:self.model.address] ) {
        self.model.address = @"";
    }
    if ([StringTool isBlankString:self.model.avatar]) {
        self.model.avatar = @"1";
    }
    if ([StringTool isBlankString:self.model.area]) {
        self.model.area = @"";
    }
    if ([StringTool isBlankString:self.model.city]) {
        self.model.city = @"";
    }
    
    self.model.consumerId = [NSString stringWithFormat:@"%zd",[UserModal shareUserModel].userId];
    self.model.detailId = [UserModal getDetailId];
}
-(void)refreshData{
    [super refreshData];
    [MBProgressHUD showMessage:@"请稍后" toView:self.view];
    
    __weak typeof(self)bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        ResulteMod *mod = [bself.dataMange getCustomerInfo];
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [MBProgressHUD hideHUDForView:bself.view animated:YES];
            
            if (mod.resltState == ResultFail) {
                [MBProgressHUD showError:mod.resultTip];
            }else if (mod.resltState == ResultNetError){
                [MBProgressHUD showError:@"网络错误"];
            }else
            {
                bself.model = [[CustModel alloc]init];
                bself.model = mod.dataMod;
                [bself upIU];
                
              
            }
        });
    });
}

-(void)keyBoardWillShow
{
    [ClearView showInView:self.view];
}
#pragma mark 检查修改的内容
-(void)checkInfo
{
    if (![StringTool isBlankString:self.trueNameEt.text]) {
        self.model.realname = self.trueNameEt.text;
    }else
    {
        self.model.realname = @"";
    }
    
    if (![StringTool isBlankString:self.phoneEt.text]) {
        self.model.mobile = self.phoneEt.text;
    }else{
        self.model.mobile = @"";
    }
    if (![StringTool isBlankString:self.emailEt.text] ) {
        
        self.model.mail = self.emailEt.text;
    }else
    {
        self.model.mail = @"";
    }
    
    if (![StringTool isBlankString:self.mobileEt.text]) {
        self.model.tel = self.mobileEt.text;
    }else
    {
        self.model.tel = @"";
    }
    
    if (![StringTool isBlankString:self.addressEt.text]) {
        
        if (self.cityName != nil ) {
            
            self.model.city = self.stateCode;
            self.cityName = self.stateName;
            self.model.area = self.cityCode;
            self.model.areaName = self.cityName;
            self.model.address = self.addressEt.text;
        }
    }else
    {
        self.model.city = @"";
        self.cityName = @"";
        self.model.area = @"";
        self.model.areaName = @"";
        self.model.address = @"";
    }
    
    if (![StringTool isBlankString:self.sexEt.text]) {
        self.model.sexName = self.sexEt.text;
        if ([self.sexEt.text isEqual:@"男"]) {
            self.model.sex = @"1";
        }else
        {
            self.model.sex = @"0";
        }
    }else
    {
        self.model.sex = @"";
        self.model.sexName = @"";
    }
    
    if (![StringTool isBlankString:self.birthEt.text]  ) {

        self.model.birthday = self.birthEt.text;
    }else
    {
        self.model.birthday = @"";
    }
    
    
    
}

#pragma mark 点击了“地址”
- (IBAction)addressBtnOnClick:(id)sender {
    
    [self.view endEditing:YES];
    if (locateView==nil) {
        locateView = [LocPickView creadInstance];
        [locateView.sureBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [locateView showInView:self.view];
}


-(void)btnOnclick:(id)sender{
    
    UIButton *btn = (UIButton *)sender;

    [self.view endEditing:YES];
    if (sender==locateView.sureBtn) {
        [locateView hide];
        
        self.cityCode = [locateView getCityCode];
        self.cityName = [locateView getCityName];
        self.stateCode = [locateView getStateCode];
        self.stateName = [locateView getStateName];
        
        self.addressEt.text = [locateView getAddress];
    
    }else if (sender == dateView.sureBtn)
    {
        [dateView hide];
        self.birthEt.text = [self stringFromDate:dateView.dataPick.date];
    
    }else if(btn.tag == 100) //保存信息
    {
        [self checkInfo];
        [self upData];
    }else if (sender == sexView.sureBtn)
    {
       
        self.sexEt.text = [sexView getInof];
         [sexView hide];
    }
    
    
}

#pragma mark 上传数据
-(void)upData
{
    [MBProgressHUD showMessage:@"请稍等" toView:self.view];
    __weak typeof(self)bself = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        ResulteMod *mod = [bself.dataMange updateCustomerInfoWithCustModel:self.model];
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:bself.view animated:YES];
            
            if (mod.resltState == ResultFail) {
                [MBProgressHUD showError:mod.resultTip];
            }else if (mod.resltState == ResultNetError)
            {
                [MBProgressHUD showError:@"网络错误"];
            }else
            {
                [bself.navigationController popViewControllerAnimated:YES];
                [MBProgressHUD showSuccess:@"保存成功"];
            }
            
        });
    });
    
}
- (NSString *)stringFromDate:(NSDate *)date{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    
    
    //zzz表示时区，zzz可以删除，这样返回的日期字符将不包含时区信息。
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    
    
    NSString *destDateString = [dateFormatter stringFromDate:date];

    return destDateString;
    
}



- (void) animateTextField: (UITextField*) textField up: (BOOL) up
{
    
    CGRect dd =  [textField.superview convertRect:textField.frame toView:self.backView];
    
    int tvbotY = dd.size.height+dd.origin.y;
    int mid  = PMH-[UserModal shareUserModel].keyboardHeight-tvbotY -64 - 5;
    if (mid<0) {
        
        
        const int movementDistance = mid; // tweak as needed
        const float movementDuration = 0.3f; // tweak as needed
        
        int movement = (up ? movementDistance : -movementDistance);
        
        [UIView beginAnimations: nil context: nil];
        [UIView setAnimationBeginsFromCurrentState: YES];
        [UIView setAnimationDuration: movementDuration];
        
        self.view.frame = CGRectOffset(self.view.frame, 0, movement);
        
        [UIView commitAnimations];
        
    }
    
}

#pragma mark 点击生日
- (IBAction)BirthDayBtnOnClick:(id)sender
{
     [self.view endEditing:YES];
    if (dateView == nil) {
        dateView = [DatePickView createView];
        [dateView.sureBtn addTarget:self action:@selector(btnOnclick:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    [dateView showInView:self.view];

}

#pragma et delegare
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [self animateTextField: textField up: YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    
    [self resetView];
    
    [textField resignFirstResponder];
    return  YES;
}

-(void)resetView
{
    const float movementDuration = 0.3f;
    [UIView beginAnimations: nil context: nil];
    [UIView setAnimationBeginsFromCurrentState: YES];
    [UIView setAnimationDuration: movementDuration];
    
    CGRect buf = self.view.frame;
    buf.origin.y =  64;
    [self.view setFrame:buf];
    [self.view endEditing:YES];
    [UIView commitAnimations];
}
- (IBAction)sexBtnOnClick:(id)sender {

     [self.view endEditing:YES];

    [sexView showhighlighted:self.sexEt.text];
    [sexView showInView:self.view];
}
- (IBAction)imgBtnOnClick {
    
    if (self.menuView==nil) {
        menuView = [PhootSelecteView creadInstance];
        [menuView.tackPicBtn addTarget:self action:@selector(btnOnclick2:) forControlEvents:UIControlEventTouchUpInside];
        [menuView.selectePicBtn addTarget:self action:@selector(btnOnclick2:) forControlEvents:UIControlEventTouchUpInside];
    }
    [menuView showInView:self.view];
}

-(void)btnOnclick2:(id)sender{
    
    if (sender==menuView.tackPicBtn) {
        
        // 跳转到相机
        NSUInteger sourceType = UIImagePickerControllerSourceTypeCamera;
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = NO;
        imagePickerController.sourceType = sourceType;
        imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [self presentViewController:imagePickerController animated:YES completion:^{}];
        
    }else if(sender==menuView.selectePicBtn){
        
        // 跳转到相册
        NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = NO;
        
        imagePickerController.sourceType = sourceType;
        imagePickerController.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
        [self presentViewController:imagePickerController animated:YES completion:^{}];
    }
}

#pragma mark  UiPickView delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    
    [picker dismissViewControllerAnimated:YES completion:^{}];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    image = [Tools fixOrientation:image];
    
    int h = [Tools getHightDifPMsW:100/2 sh:100/2 nw:PMW];
    CGRect buf = CGRectMake(0, PMH/2-h/2,PMW, h);
    
    // 裁剪
    VPImageCropperViewController *imgEditorVC = [[VPImageCropperViewController alloc] initWithImage:image cropFrame:buf limitScaleRatio:6];
    imgEditorVC.delegate = self;
    [self presentViewController:imgEditorVC animated:YES completion:^{}];
    
}



- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:^{}];
}





#pragma mark VPImageCropperDelegate
- (void)imageCropper:(VPImageCropperViewController *)cropperViewController didFinished:(UIImage *)image {
    
    [cropperViewController dismissViewControllerAnimated:YES completion:^{}];
    
    image = [Tools imageWithImageSimple:image scaledToSize:CGSizeMake(100, 100)];
    
    [self upImg:image];
}



- (void)imageCropperDidCancel:(VPImageCropperViewController *)cropperViewController {
    
    [cropperViewController dismissViewControllerAnimated:YES completion:^{}];
}

#pragma mark 上传头像
-(void)upImg:(UIImage*)img{
    
    [menuView hide];
    
    [dm upHeadImg:img View:self.headBtn];
}


@end
